#include "arch/loongarch.h"
#include "boot/boot_param.h"
#include "lib/stdio.h"

extern void mmu_init(void);
extern void kinit(void);
extern void vminit(void);
extern void procinit(void);
extern void trap_init(void);
extern void stdin_init(void);

// ASM
extern void move_to_user_mode(void);

void module_init() {
    pr_info(module_init, "Memory Management Unit");
    mmu_init();
    pr_info(module_init, "Physical Memory Allocation");
    kinit();
    pr_info(module_init, "Virtual Memory Allocation");
    vminit();
    pr_info(module_init, "Process Table");
    procinit();
    pr_info(module_init, "Kernel Trap");
    trap_init();
    pr_info(module_init, "Standard Input/Output Buffer");
    stdin_init();
    pr_info(module_init, "First User Process");
    userinit();	
}

void kernel_entry(int a0, char **args, struct bootparamsinterface *a2) {
    // 显示 BIOS 传递参数信息
    int i;
    pr_info(kernel_entry, "There is %d args for kernel:", a0);
    for (i = 0; i < a0; i++) {
        pr_info(bios_argv, "cmd arg %d: %s", i, args[i]);
    }
    pr_info(kernel_entry, "efi system table at %p", a2->systemtable);
    pr_info(kernel_entry, "efi extend list at %p", a2->extlist);

    // 各功能模块初始化
    module_init();
    // LOGO 显示
    display_logo();

    // 要求编译器和处理器不要在这一点上移动加载或存储，保证前面的任务完成
	__sync_synchronize();

    // TODO: 跳转到用户态
    // pr_info(kernel_entry, "Switching to user mode ...\n");
    move_to_user_mode();

    while (true) {
        panic(kernel_entry, "How did you run here :D");
    }
}
